// 导入模块
const dbApi = require('../models/db')
const jwt = require('../utils/jwt')
const { uuid, refresh_uuid } = require('../config/config.default')
// const multer = require('multer')
const { body } = require('express-validator')

// 用户登录
exports.login = async (req, res, next) => {
  let { mobile, code } = req.body
  mobile = parseInt(mobile)
  code = parseInt(code)
  const checkCode = 123456
  if (code !== checkCode) {
    res.status(401).json({
      message: '验证码错误'
    })
    return
  }
  try {
    const sql = `SELECT username FROM users WHERE mobile =${mobile} `
    const [data] = await dbApi.query(sql)
    if (data) {
      // 用户存在
      // 生成用户使用token
      const token = await jwt.sign({ uid: data.username }, uuid, {
        expiresIn: '2h'
      })
      // 生成用于刷新token
      const refresh_token = await jwt.sign(
        { uid: data.username },
        refresh_uuid,
        {
          expiresIn: '7 days'
        }
      )
      res.status(200).json({
        message: 'success',
        data: {
          token,
          refresh_token
        }
      })
    } else {
      // 没有这个用户
      const sql = `INSERT INTO users (username,mobile,password,gender)
        VALUES('${mobile}',${mobile},123456,0)`
      await dbApi.query(sql)
      const token = await jwt.sign({ udi: mobile }, uuid, {
        expiresIn: '2h'
      })
      res.status(200).json({
        message: 'success',
        token
      })
    }
  } catch (error) {
    next(error)
  }
}

// 获取当前用户信息
exports.getUser = async (req, res, next) => {
  try {
    // 处理请求
    res.status(201).json({
      data: req.user,
      message: 'success'
    })
  } catch (error) {
    next(error)
  }
}

// 获取用户频道
exports.getUserChannels = async (req, res, next) => {
  let token = req.headers.authorization
  token = token ? token.split('Bearer ')[1] : null
  if (!token) {
    return res.status(201).json({
      channels: [
        { division: '推荐', id: 0 },
        { division: 'javascript', id: 1 },
        { division: 'vue', id: 2 },
        { division: 'node', id: 3 },
        { division: 'java', id: 4 },
        { division: '区块链', id: 5 }
      ],
      message: 'success'
    })
  }
  try {
    const userInfo = await jwt.verify(token, uuid)
    const sql = `SELECT a.id,a.division FROM channel a  INNER JOIN userchannle b 
    ON a.id = b.channel_id WHERE b.username ='${userInfo.uid}'`
    const data = await dbApi.query(sql)
    // 处理请求
    res.status(201).json({
      channels: data,
      message: 'success'
    })
  } catch (error) {
    next(error)
  }
}

// //更新用户信息
exports.updateUserInfo = async (req, res, next) => {
  const { nickname = null, gender = null, birthday = null } = req.body
  const username = req.user.username
  try {
    if (nickname) {
      // 昵称存在，修改昵称
      // 当前修改昵称是否存在
      const selsql = `SELECT * FROM users WHERE nickname ='${nickname}'`
      const [seldata] = await dbApi.query(selsql)
      if (seldata) {
        // 有，则昵称存在
        res.status(409).json({
          message: 'succesed'
        })
      } else {
        const updatenamesql = `UPDATE users SET nickname = '${nickname}' 
        WHERE  username = '${username}'`
        const { affectedRows: rows } = await dbApi.query(updatenamesql)
        rows > 0
          ? res.status(201).json({
            message: 'succesed'
          })
          : res.status(401).json({
            message: 'Modification failure'
          })
      }
      return
    }
    if (gender !== null) {
      // 性别存在，修改昵称
      const updatenamesql = `UPDATE users SET gender = ${gender} 
      WHERE  username = '${username}'`
      const { affectedRows: rows } = await dbApi.query(updatenamesql)
      rows > 0
        ? res.status(201).json({
          message: 'succesed'
        })
        : res.status(401).json({
          message: 'Modification failure'
        })
      return
    }
    if (birthday) {
      // 生日存在，修改昵称
      const updatenamesql = `UPDATE users SET birthday = '${birthday}' 
      WHERE  username = '${username}'`
      const { affectedRows: rows } = await dbApi.query(updatenamesql)
      rows > 0
        ? res.status(201).json({
          message: 'succesed'
        })
        : res.status(401).json({
          message: 'Modification failure'
        })
      return
    }
  } catch (error) {
    next(error)
  }
}

// 更新用户头像
exports.updateUserAratar = async (req, res, next) => {
  const username = req.user.username
  try {
    const sql = `UPDATE  users set
    avatar = 'http://localhost:3000/public/users/image/${req.file.filename}'
    WHERE username = '${username}'`
    // 处理请求
    const { affectedRows: rows } = await dbApi.query(sql)
    rows > 0
      ? res.status(201).json({
        message: 'succesed'
      })
      : res.status(201).json({
        message: 'Modification failure'
      })
  } catch (error) {
    next(error)
  }
}

// 更新用户token
exports.updateUserToken = async (req, res, next) => {
  const { username } = req.user
  try {
    // 重新生成token
    const token = await jwt.sign({ uid: username }, uuid, {
      expiresIn: '2h'
    })
    // 生成用于刷新token
    const refresh_token = await jwt.sign({ uid: username }, refresh_uuid, {
      expiresIn: '7 days'
    })
    res.status(200).json({
      message: 'success',
      data: {
        token,
        refresh_token
      }
    })
  } catch (error) {
    next(error)
  }
}
